import Dep from './dep.js'
import { compileProp } from './compiler.js'

class Watcher {
  constructor (vm, prop, callback) {
    this.vm = vm
    this.prop = prop
    this.callback = callback
    // 把watcher对象记录到Dep类的静态属性target
    Dep.target = this
    // 访问vm[prop]的get方法把watcher添加到dep
    // this.oldValue = vm[prop]
    this.oldValue = compileProp(vm, prop)
    // 重置Dep.target
    Dep.target = null
  }

  update () {
    // const newValue = this.vm[this.prop]
    const newValue = compileProp(this.vm, this.prop)
    if (this.oldValue === newValue) return
    this.callback(newValue)
  }
}

export default Watcher
